<?php

declare(strict_types=1);

namespace App\Controller;

use App\Model\Member;
use Hyperf\Redis\Redis;
use Hyperf\ViewEngine\Contract\FactoryInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Hyperf\HttpServer\Response;
use RedisException;
use Trait\ResponseMsg;
use Hyperf\Di\Annotation\Inject;
use Util\Common;

/**
 * 微信公众号回调控制器
 */
class WechatController extends AbstractController
{
    use ResponseMsg;


    protected Redis $redis;
    protected string $token = 'mihetong';

    #[Inject]
    protected Member $member;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
    }

    public function index(RequestInterface $request, Response $response)
    {

//        $params = $request->query();
        $result = $this->valid($request);
        return $response
        ->raw($result)
        ->withAddedHeader('Content-Type', 'application/xml');
    }

    /**校验
     * @param $params
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function valid(RequestInterface $request)
    {
        $params = $request->query();
        if (isset($params['echostr'])) {
            $echoStr = $params["echostr"];
            if($this->checkSignature($params)){
                return  $echoStr;
            }
        } else {
            return $this->responseMsg($request);
        }
    }

    /**查看签名
     * @param $params
     * @return bool
     */
    public function checkSignature($params)
    {
        $signature = $params["signature"];
        $timestamp = $params["timestamp"];
        $nonce = $params["nonce"];
        $tmpArr = array($this->token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    /**
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    private function responseMsg(RequestInterface $request)
    {

        $postArr = $request->getBody()->getContents();
        $postObj = simplexml_load_string($postArr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $postObj=json_decode(json_encode($postObj),true);
        $msgType = $postObj['MsgType'];
        $result ='';
        switch ($msgType) {
            case 'event':
                $openid = $postObj['FromUserName'];
                $eventKey = $postObj['EventKey'];
                $eventKey = str_replace("qrscene_", "", $eventKey);
                $from = $postObj['ToUserName'];
                $result =$this->qrCodeLogin($openid,$eventKey,$from);
                break;
            case 'text':
//              file_put_contents('a.txt',json_encode(['a3'=>$postObj['FromUserName']]));
                break;
            default:
                // code...
                break;
        }
        // file_put_contents('a.txt',json_encode(['user'=>$postObj->ToUserName,'token'=>$postObj->EventKey]));
        return $result;
    }

    /**登陆成功
     * @param $openid
     * @param $token
     * @param $from
     * @return ResponseInterface|void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    private function qrCodeLogin($openid,$token,$from)
    {
        $user = $this->member->where('openid',$openid)->first();
        if($user){
            if($user->status == Common::MEMBER_STATUS_ERROR){
                $response = container()->get(\Hyperf\HttpServer\Contract\ResponseInterface::class);
                return $response->json(['code' => 1002, 'msg' => '当前用户已被禁用']);
            }
            $user->batoken=$token;
            $user->lastlogintime = time();
            $user->save();
        } else {
            $data = [
                'status' => 'enable',
                'nickname' => '微信用户'.time(),
                'openid' => $openid,
                'batoken' => $token,
                'Login_type' => 1
            ];
           $user =  Member::create($data);
        }
        $msg_tpl = '<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>';
        $result =  sprintf($msg_tpl,$openid, $from, time(), '登陆成功!');
        return $result;
    }

}
